home *** CD-ROM | disk | FTP | other *** search
/ Pascal Super Library / Pascal Super Library (CW International)(1997).bin / LIBRARY / PAS_0493 / SQRTAPRX.PAS < prev    next >
Pascal/Delphi Source File  |  1993-04-15  |  2KB  |  60 lines

  1. {─ Fido Pascal Conference ────────────────────────────────────────────── PASCAL ─
  2. Msg  : 309 of 318
  3. From : Bob Swart                           2:281/256.12         09 Apr 93  17:04
  4. To   : Manh Tran                           1:273/704.0
  5. Subj : Bug In Pascal Code
  6. ────────────────────────────────────────────────────────────────────────────────
  7. Hi Manh!
  8.  
  9.  > Does anyone see what is wrong with the following pascal code.
  10. Yes, the bug is in your until-statement, you continue to run
  11.  
  12.  >   Until (est = factor) or (est = factor+0.01) or (est = factor-0.01);
  13. i.e. until you have one of three EXACT MATCHES!!
  14.  
  15. If there's one thing you cannot rely on, it's exact matches with reals.
  16.  
  17. It is obvious you want to terminate the loop if est is within the range
  18. [factor-@,factor+@], where @ is some sort of accuracy you can get with reals.
  19. Since reals are accurate to 11 digits, you should divide the factor by the est
  20. (or the other way around if you like), and see if the resulting quotient minus
  21. one (ans the absolute value of that result) is less of equal 10 times the
  22. negative number of significant digits you want.
  23.  
  24. Like this:
  25.  
  26.   until abs(1-(factor/est)) <= delta;
  27.  
  28. if you want 2 significant digits, you should set delta to 0.01 (1e-2), etc.
  29.  
  30. To clearify all this, look at the modified code for 4 significant digits: }
  31.  
  32.  
  33. Program SQRT_approx;
  34. Uses Crt;
  35. Const delta = 1e-4;
  36. var Num,i: LongInt;
  37.     Est, new_est, factor: Real;
  38. begin
  39.   Clrscr;
  40.   write('Enter a number: ');
  41.   readln(Num);
  42.   writeln;
  43.   if Num > 0 then
  44.   begin
  45.     i := 1;
  46.     Est := Num / 2;
  47.     writeln('REAL Square root of ',Num,' is ',sqrt(Num):6:4);
  48.     writeln;
  49.     writeln('Estimate       Factor     New_est   # Of Oper. ');
  50.     repeat
  51.       Factor := Num / est;
  52.       New_est := (est + factor) / 2 ;
  53.       writeln(est:8:4, factor:11:4, New_est:14:4,i:8);
  54.       Inc(i) ;
  55.       est := new_est
  56.     until abs(1-(factor/est)) <= delta
  57.   end
  58.   else
  59.     writeln('Error: cannot calculate the square root of a negative number.')
  60. end.